$(window).load(function(){
	try
    {
		$("div.acl").jstree({
			"plugins" : [ "themes", "html_data", "checkbox" ],
			"themes" : {
				"theme" : "default",
				"dots" : true,
				"icons" : true
			},
			"checkbox" : {
				real_checkboxes : true
			}
		});
        
        setTimeout("waitSometime()", 1000);
	}catch(e){
	   alert(e);
	}
});
var delay = 2;
function waitSometime() {delay--; if (delay == 0) {initACLlist();} else {setTimeout("waitSometime()", 1000);}}

function initACLlist () {
    $("div.acl").each(function(){
        var eltParentId = $(this).attr('id');
        $("li.action", this).each(function() {
            loadRule($(this).attr('id'), $("input[name='id_role']").val(), $("input[name='id_user']").val(), eltParentId);
		});
	});
}

/**
 *load the ACL of a role type
 */
 function loadRule(resourceId, roleId, userId, eltParentId)
 {
	try{
		$.ajax({
			type     : 'POST',
			dataType : 'json',
            data     : 'id_ressource=' + resourceId + '&id_role=' + roleId + '&id_user=' + userId,
			cache    : false,
			url      : baseUrl + 'xhr/userroles/acl',
			success  : function(response){
                if (response)
                {
                    if (eltParentId == 'acl_entity_fields') {
                        $.jstree._reference("div.acl#acl_entity_fields").uncheck_node('li#' + resourceId);
        				
    					if(response == true)
                        {
    						$.jstree._reference("div.acl#acl_entity_fields").check_node('li#' + resourceId);
    					}
                    } else if (eltParentId == 'acl_url_fields') {
        				$.jstree._reference("div.acl#acl_url_fields").uncheck_node('li#' + resourceId);
        				
    					if(response == true)
                        {
    						$.jstree._reference("div.acl#acl_url_fields").check_node('li#' + resourceId);
    					}
                    }
    				return;
                }
				return;
			},
			error:function(xhr,err){
				//manage errors
			}
		});
	}catch(e){
		//alert(e);
	}
}